#include<iostream>
#include<unordered_map>
using namespace std;

unordered_map<string, string> f;

string findfa(string x) {
    return f[x] = f[x] == x ? x : findfa(f[x]);
}

int main() {
    string str, fa, son;
    while(cin >> str) {
        if(str[0] == '$')   return 0;
        if(str[0] == '#') {
            fa = str.substr(1);
            if(!f.count(fa))    f[fa] = fa;
        }
        if(str[0] == '+') {
            son = str.substr(1);
            f[son] = findfa(fa);
        }
        if(str[0] == '?') {
            son = str.substr(1);
            cout << son << " " << findfa(son) << endl;
        }
    }
    return 0;
} 